package cn.sciento.farm.devicemanager.gateway.downlink.service.impl;

import cn.sciento.farm.devicemanager.common.constant.MqttConstant;
import cn.sciento.farm.devicemanager.gateway.downlink.service.MqttCallBackFuture;
import cn.sciento.farm.devicemanager.gateway.model.downlink.AbstractBlockData;
import cn.sciento.farm.devicemanager.gateway.model.downlink.fertilizer.FertilizerControlData;
import cn.sciento.farm.devicemanager.gateway.model.uplink.FertilizerUplinkPacket;
import cn.sciento.farm.devicemanager.gateway.uplink.service.fertilizer.FertilizerDisposeService;
import com.alibaba.fastjson.JSON;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.Map;

@Order(3)
@Service
public class FertilizerDataService implements FertilizerDisposeService {
    @Override
    public void handleUplinkPacket(String eui, FertilizerUplinkPacket uplinkPacket) {
        if (!uplinkPacket.isSensorData()) {

            MqttCallBackFuture mqttCallBackFuture = MqttCallBackFuture.futurePool.get(
                    String.format(
                            MqttConstant.FERTILIZER_CONTROL_SUB_BLOCK_ID,
                            eui,
                            uplinkPacket.getChannel()
                    )
            );
            if (mqttCallBackFuture == null) {
                return;
            }
            AbstractBlockData abstractBlockData = mqttCallBackFuture.getAbstractBlockData();

            if (abstractBlockData instanceof FertilizerControlData) {
                if (uplinkPacket.getStirringMotor() != null || uplinkPacket.getFertilizeValve() != null) {
                    FertilizerControlData controlData = (FertilizerControlData) abstractBlockData;
                    if (uplinkPacket.getStirringMotor() != null) {
                        if (uplinkPacket.getStirringMotor().equals(controlData.getStirringMotor())) {
                            mqttCallBackFuture.setResponse("");
                        }
                    }
                    if (uplinkPacket.getFertilizeValve() != null) {
                        if (uplinkPacket.getFertilizeValve().equals(controlData.getFertilizeValve())) {
                            mqttCallBackFuture.setResponse("");
                        }
                    }
                } else {
                    mqttCallBackFuture.setResponse("");
                }
                return;
            }
            mqttCallBackFuture.setResponse("");

        }
    }

    @Override
    public void updateOnline(String concentrator, int status) {

    }
}
